const Core = require('./core/Core');
const os = require('os');
const fs = require('fs');
const ini = require('ini');
const Logger = require('avenir-log');
async function init() {


    let file = await giveFileName();
    let ini = await readIni(file);
    let log = new Logger('main', './log');
    log.noDebug();
    global.log = log;
    global.ini = ini;
    let mq = new Core();
    bless();
    await mq.init("127.0.0.1", ini.main.port);//启动sock

}

async function main() {
    await init();
}


async function giveFileName() {
    let type = os.platform();
    let fileName;
    if (type == "darwin") {
        fileName = "/Users/hideyoshi/Desktop/codes/AvenirMQ/run.ini";

    }
    else if (type == "win32") {
        fileName = "F:/AvenirMQ/run.ini";

    }
    else {
        fileName = "./run.ini"

    }
    return fileName;
}


async function readIni(fileName) {
    if(!fs.existsSync(fileName)) {
        defalutIni(fileName);
    }
    let file = fs.readFileSync(fileName);
    try {
        var Info = ini.parse(file.toString());
        return Info;
    } catch(error) {
        return defalutIni(fileName);
    }
    
}

function bless() {
    console.log(`
       ┌─┐       ┌─┐
    ┌──┘ ┴───────┘ ┴──┐
    │                 │
    │       ───       │
    │  ─┬┘       └┬─  │
    │                 │
    │       ─┴─       │
    │                 │
    └───┐         ┌───┘
        │         │
        │         │
        │         │
        │         └──────────────┐
        │                        │
        │                        ├─┐
        │                        ┌─┘
        │                        │
        └─┐  ┐  ┌───────┬──┐  ┌──┘
          │ ─┤ ─┤       │ ─┤ ─┤
          └──┴──┘       └──┴──┘
              神兽保佑
              代码无BUG!`);

    console.log(`
     _______  __   __  _______  __    _  ___   ______    __   __  _______ 
    |   _   ||  | |  ||       ||  |  | ||   | |    _ |  |  |_|  ||       |
    |  |_|  ||  |_|  ||    ___||   |_| ||   | |   | ||  |       ||   _   |
    |       ||       ||   |___ |       ||   | |   |_||_ |       ||  | |  |
    |       ||       ||    ___||  _    ||   | |    __  ||       ||  |_|  |
    |   _   | |     | |   |___ | | |   ||   | |   |  | || ||_|| ||      | 
    |__| |__|  |___|  |_______||_|  |__||___| |___|  |_||_|   |_||____||_|`);
}


function defalutIni(fileName) {
    const data = {
        main: { ip: '127.0.0.1', port: '52013' },
        mq: {
          userFileName: './user.json',
          ifConsoleLog: true,
          timeOut: '10',
          keepAlive: true,
          MQTimeOut: '3',
          MQResend: '2',
          retryTime: '5',
          loopTime: '10',
          connClearTime: '20',
          signClearTime: '20',
          autoClear:'120',
        }
      }
    fs.writeFileSync(fileName,ini.stringify(data));
    return data;
}

main();